package mx.itesm.ccm.compu.gui;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import mx.itesm.ccm.compu.gui.AsesoriasApplication;
import mx.itesm.ccm.compu.gui.MainPanel.Rol;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.vaadin.Application;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Label;
import com.vaadin.ui.LoginForm;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Window;
import com.vaadin.ui.LoginForm.LoginEvent;
import com.vaadin.ui.LoginForm.LoginListener;
import com.vaadin.ui.Window.Notification;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Login extends Window {
	
	Logger log = LoggerFactory.getLogger(Login.class);
	private Panel login;

	public Login() {
		super();
		configureWindow();
	}

	public Login(String caption, ComponentContainer content) {
		super(caption, content);
		configureWindow();
	}

	public Login(String caption) {
		super(caption);
		configureWindow();
	}

	public void createLoginForm() {
		// TODO Auto-generated method stub
		login = new Panel();

		login.setSizeFull();

		LoginForm l = new LoginForm() {
			@Override
			protected byte[] getLoginHTML() {
				byte[] htmlBytes = super.getLoginHTML();
				String htmlString = new String(htmlBytes);

				htmlString = htmlString.replace("Username", "Usuario");
				htmlString = htmlString.replace("Password", "Clave");
				htmlString = htmlString.replace("Login", "Entrar");
				return htmlString.getBytes();
			}
		};

		l.addListener(new LoginListener() {

			public void onLogin(LoginEvent event) {
				
				
				log.debug("Entro a login");
				String status = "";
				try {

					String data = URLEncoder.encode("username", "UTF-8")
							+ "="
							+ URLEncoder.encode(
									event.getLoginParameter("username"),
									"UTF-8");
					data += "&"
							+ URLEncoder.encode("password", "UTF-8")
							+ "="
							+ URLEncoder.encode(
									event.getLoginParameter("password"),
									"UTF-8");
					URL url = new URL(
							"http://escolares.ccm.itesm.mx/~mobile/autentica/funcLDAP.php");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					OutputStreamWriter writer = new OutputStreamWriter(conn
							.getOutputStream());

					writer.write(data);
					writer.flush();

					Reader rd = new InputStreamReader(conn.getInputStream());
					JSONTokener jt = new JSONTokener(rd);
					JSONObject res = new JSONArray(jt).getJSONObject(0);
					
					log.debug("respuesta json {}", res);
					
					status = res.getString("Estatus");
					log.debug("Estatus es {}" , status);
				
					
					writer.close();
					rd.close();

				} catch (Exception ex) {
					ex.printStackTrace();
				}

				if (status.equals("ok")) {
					
				
					String user = event.getLoginParameter("username");
					
					AsesoriasApplication.getInstance().setUser(user);
					
					log.debug("user: {}" , AsesoriasApplication.getInstance().getUser());
					
					if (user.startsWith("a") || user.startsWith("A")) {
						// TODO Mandar a alumno
						((AsesoriasApplication)getApplication()).createWindow(Rol.ALUMNO);
					} else {
						// Mandar a profesor
						((AsesoriasApplication)getApplication()).createWindow(Rol.PROFESOR);
					}
					event.getComponent().getApplication().getMainWindow().removeWindow(event.getComponent().getWindow());
	
				} else {

				}
			}
		});

		login.addComponent(l);

		this.addComponent(login);
	}

	private void configureWindow() {
		this.setModal(true);
		this.setClosable(false);
		this.setDraggable(false);
		this.setResizable(false);

		this.setSizeFull();

		createLoginForm();

	}

}
